package com.example.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crm.entity.Opportunity;
import com.example.crm.mapper.OpportunityMapper;
import com.example.crm.service.ContactService;
import com.example.crm.service.CustomerService;
import com.example.crm.service.OpportunityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售机会服务实现类
 */
@Service
public class OpportunityServiceImpl extends ServiceImpl<OpportunityMapper, Opportunity> implements OpportunityService {

    @Autowired
    private CustomerService customerService;
    
    @Autowired
    private ContactService contactService;
    
    @Override
    public IPage<Opportunity> listOpportunitiesByPage(Map<String, Object> params) {
        int current = Integer.parseInt(params.getOrDefault("current", "1").toString());
        int size = Integer.parseInt(params.getOrDefault("size", "10").toString());
        
        Page<Opportunity> page = new Page<>(current, size);
        QueryWrapper<Opportunity> queryWrapper = new QueryWrapper<>();
        
        // 根据客户ID筛选
        if (params.containsKey("customerId") && params.get("customerId") != null) {
            queryWrapper.eq("customer_id", params.get("customerId"));
        }
        
        // 根据机会名称筛选
        if (params.containsKey("name") && StringUtils.isNotBlank(params.get("name").toString())) {
            queryWrapper.like("name", params.get("name"));
        }
        
        // 根据机会阶段筛选
        if (params.containsKey("stage") && params.get("stage") != null) {
            queryWrapper.eq("stage", params.get("stage"));
        }
        
        // 根据负责人筛选
        if (params.containsKey("managerId") && params.get("managerId") != null) {
            queryWrapper.eq("manager_id", params.get("managerId"));
        }
        
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        
        IPage<Opportunity> result = page(page, queryWrapper);
        
        // 填充客户名称和联系人名称
        result.getRecords().forEach(opportunity -> {
            if (opportunity.getCustomerId() != null) {
                opportunity.setCustomerName(customerService.getById(opportunity.getCustomerId()).getName());
            }
            if (opportunity.getContactId() != null) {
                opportunity.setContactName(contactService.getById(opportunity.getContactId()).getName());
            }
            // 设置阶段名称
            opportunity.setStageName(getStageName(opportunity.getStage()));
        });
        
        return result;
    }

    @Override
    public Opportunity getOpportunityDetail(Long id) {
        Opportunity opportunity = getById(id);
        if (opportunity != null) {
            // 设置客户名称
            if (opportunity.getCustomerId() != null) {
                opportunity.setCustomerName(customerService.getById(opportunity.getCustomerId()).getName());
            }
            // 设置联系人名称
            if (opportunity.getContactId() != null) {
                opportunity.setContactName(contactService.getById(opportunity.getContactId()).getName());
            }
            // 设置阶段名称
            opportunity.setStageName(getStageName(opportunity.getStage()));
        }
        return opportunity;
    }

    @Override
    public List<Opportunity> getOpportunitiesByCustomerId(Long customerId) {
        return baseMapper.selectByCustomerId(customerId);
    }

    @Override
    public Map<String, Object> getSalesFunnelData() {
        Map<String, Object> funnelData = baseMapper.getSalesFunnelData();
        
        // 将阶段转换为阶段名称
        Map<String, Object> result = new HashMap<>();
        result.put("初步接洽", funnelData.get("stage1"));
        result.put("需求确认", funnelData.get("stage2"));
        result.put("方案制定", funnelData.get("stage3"));
        result.put("商务谈判", funnelData.get("stage4"));
        result.put("赢单", funnelData.get("stage5"));
        result.put("输单", funnelData.get("stage6"));
        
        return result;
    }

    @Override
    public Map<String, Object> getSalesStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 销售机会总数
        long totalCount = count(new LambdaQueryWrapper<Opportunity>().eq(Opportunity::getDeleted, 0));
        statistics.put("totalCount", totalCount);
        
        // 销售机会总金额
        QueryWrapper<Opportunity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(SUM(expected_amount), 0) as total_amount");
        queryWrapper.eq("deleted", 0);
        Map<String, Object> resultMap = getMap(queryWrapper);
        BigDecimal totalAmount = new BigDecimal(resultMap.get("total_amount").toString());
        statistics.put("totalAmount", totalAmount);
        
        // 本月新增销售机会数
        Long newCount = baseMapper.countNewOpportunitiesThisMonth();
        statistics.put("newCount", newCount);
        
        // 本月新增销售机会金额
        BigDecimal newAmount = baseMapper.sumNewOpportunityAmountThisMonth();
        statistics.put("newAmount", newAmount);
        
        // 各阶段销售机会数量
        statistics.put("stageStats", baseMapper.countGroupByStage());
        
        return statistics;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOpportunityStage(Long id, Integer stage, String reason) {
        Opportunity opportunity = getById(id);
        if (opportunity == null) {
            return false;
        }
        
        opportunity.setStage(stage);
        opportunity.setUpdateTime(LocalDateTime.now());
        
        // 如果是赢单或输单，记录原因
        if (stage == 5 || stage == 6) {
            opportunity.setReason(reason);
        }
        
        return updateById(opportunity);
    }

    @Override
    public boolean addOpportunity(Opportunity opportunity) {
        opportunity.setCreateTime(LocalDateTime.now());
        opportunity.setUpdateTime(LocalDateTime.now());
        opportunity.setDeleted(0);
        return save(opportunity);
    }

    @Override
    public boolean updateOpportunity(Opportunity opportunity) {
        opportunity.setUpdateTime(LocalDateTime.now());
        return updateById(opportunity);
    }

    @Override
    public Long countNewOpportunitiesThisMonth() {
        return baseMapper.countNewOpportunitiesThisMonth();
    }

    @Override
    public BigDecimal sumNewOpportunityAmountThisMonth() {
        return baseMapper.sumNewOpportunityAmountThisMonth();
    }
    
    /**
     * 获取阶段名称
     */
    private String getStageName(Integer stage) {
        if (stage == null) {
            return "";
        }
        switch (stage) {
            case 1:
                return "初步接洽";
            case 2:
                return "需求确认";
            case 3:
                return "方案制定";
            case 4:
                return "商务谈判";
            case 5:
                return "赢单";
            case 6:
                return "输单";
            default:
                return "";
        }
    }
} 